package com.lecyon.farm.handler;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.lecyon.farm.common.exception.FarmException;
import com.lecyon.farm.vo.sync.SyncResponse;
import feign.FeignException;
import feign.Response;
import feign.codec.ErrorDecoder;

import java.io.IOException;

/**
 * @author Yao Zheng
 * @Date 2020/4/14 11:09
 */
public class FeignErrorDecoder implements ErrorDecoder {

    private Gson gson;

    public FeignErrorDecoder(Gson gson) {
        this.gson = gson;
    }

    @Override
    public Exception decode(String methodKey, Response response) {
        SyncResponse result = new SyncResponse();
        if (response.status() == 417) {
            try {
                result = gson.fromJson(response.body().asReader(),
                        SyncResponse.class);
                throw new FarmException(result.getNStatus(), result.getNDesc());
            } catch (JsonSyntaxException | JsonIOException | IOException e) {

                throw new FarmException(result.getNStatus(), result.getNDesc());
            }
        }
        throw FeignException.errorStatus(methodKey, response);
    }
}
